import NextAuth from 'next-auth'
import authConfig from './auth.config'

import { PrismaClient } from '@prisma/client'
import { PrismaAdapter } from '@auth/prisma-adapter'
import { createTeam } from '@/models/team'
import { nanoid } from 'nanoid'
import { getUser } from '@/models/user'

const prisma = new PrismaClient()

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  session: { strategy: 'jwt' },
  ...authConfig,
  pages: {
    signIn: '/login',
    signOut: '/logout',
  },
  callbacks: {
    async authorized({ request, auth }) {
      // Logged in users are authenticated, otherwise redirect to login page
      return !!auth
    },
    async signIn({ user }: any) {
      const teamName = `${user?.name}的团队`
      const teamSlug = `${user?.name}-project-${nanoid(8)}`
      if (!user?.currentTeam) {
        // 创建团队
        const team = await createTeam(user.id, {
          name: teamName,
          slug: teamSlug,
          image: `https://api.dicebear.com/9.x/bottts-neutral/svg?seed=${teamName}`,
        })
      }
      return true
    },
    // async redirect({ url, baseUrl }) {
    //   // 登录成功后跳转到的页面
    //   return url.startsWith(baseUrl) ? url : baseUrl // 或者你可以返回任意其他 URL
    // },
    jwt({ token, user }: any) {
      if (user) {
        // User is available during sign-in
        token.id = user.id
      }
      return token
    },
    async session({ session, token }: any) {
      session.user.id = token.id
      return {
        ...session,
        user: {
          ...session.user,
          id: token.id,
          ...(await getUser(token.id)),
        },
      }
    },
  },
})
